﻿using System.Diagnostics;
using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace 请求响应加密.Middle
{
    public class ApiExecuteTimeHandle
    {
        private readonly ISqlSugarClient DB;
        private readonly IConfiguration _configuration;
        private readonly RequestDelegate _next;

        public ApiExecuteTimeHandle(IConfiguration configuration,RequestDelegate next)
        {
            _configuration = configuration;
            _next = next;
            DB = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = _configuration.GetValue<string>("ConnectionStrings:url"),
                DbType = DbType.MySql,
                IsAutoCloseConnection = true
            });
        }

        public async Task Invoke(HttpContext context)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            string ip = context.Connection.RemoteIpAddress.ToString();
            string url = context.Request.Path.Value;
            string method = context.Request.Method;
            string queryString = context.Request.QueryString.Value;

            await _next(context);

            int statusCode = context.Response.StatusCode;
            stopwatch.Stop();
            // 毫秒
            //long timeCount = stopwatch.ElapsedMilliseconds;
            //ApiAccessLog model = new ApiAccessLog()
            //{
            //    Url = url,
            //    Method = method,
            //    QueryString = queryString,
            //    OriginIP = ip,
            //    ExecuteTime = timeCount,
            //    StatusCode = statusCode,
            //    AccessTime = DateTime.Now,
            //};
            //await DB.Insertable<ApiAccessLog>(model).ExecuteCommandAsync();
        }
    }
}
